<template>
	<ConfModuleContainer :show-page-tools="false">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				style="margin-right: 10px; vertical-align: middle; cursor: pointer"
				@click="router.go(-1)"
			/>
			<p class="detail-title font-20-bold">{{ currentTitle }}</p>
		</template>
		<template #Slot-Conf-Module-Content>
			<div class="description-box">
				<div class="item">
					<div class="label">版本号</div>
					<div class="value">{{ route.query?.version }}</div>
				</div>
				<div class="item">
					<div class="label">类型</div>
					<div class="value">{{ cType }}</div>
				</div>
				<div class="item">
					<div class="label">内容描述</div>
					<div class="value" :title="versionDescription">
						{{ route.query?.versionDescription }}
					</div>
				</div>
			</div>
			<div class="action-box">
				<a-button v-if="g6Permission.showBtn('upgrade-again')" type="primary" @click="PageButtonClick('update-device')">
					选择升级设备
				</a-button>
			</div>
			<div style="padding-bottom: 20px">
				<GlobalTable
					:data-source="tableAttr.data"
					:loading="tableAttr.loading"
					:columns="columns"
					:show-operation="showOperation"
					:use-select="false"
					@sort="sort"
				>
					<template #status="{ record }">
						<div class="type"><span v-if="record.status === 1" class="type-dot"></span>{{ cStatus(record.status) }}</div>
					</template>
					<template #operation="{ record }">
						<div
							v-if="g6Permission.showBtn('upgrade-again') && record.status === 1"
							class="font-14 operation-item-btn"
							@click="PageButtonClick('upgrade-again', record)"
						>
							重新升级
						</div>
					</template>
				</GlobalTable>

				<GlobalPagination
					style="margin-top: 32px"
					:current="tableAttr.current"
					:page-size="tableAttr.pageSize"
					:total="tableAttr.total"
					@change="setTablePagination"
				/>
			</div>
			<!-- 选择升级设备 -->
			<a-modal
				v-if="chooseDeviceVisible"
				:centered="true"
				class="choose-device-update"
				:open="chooseDeviceVisible"
				width="600px"
				:body-style="{ padding: '40px 32px' }"
				ok-text="确定"
				title="选择升级设备"
				:confirm-loading="confirmLoading"
				@cancel="closeDeviceUpdate"
				@ok="onSubmitName"
			>
				<div class="table-box">
					<a-table
						ref="tableRef"
						style=""
						:data-source="dialogSataSource"
						:row-selection="rowSelection"
						:row-key="rowKey"
						:destroy-on-close="true"
						size="small"
						:scroll="{ y: 266 }"
						:columns="updateColumns"
						:pagination="false"
					>
						<template #bodyCell="{ column, record }">
							<div v-if="!cColumnItem(column).custom">
								<a-tooltip placement="topLeft">
									<template #title>
										{{ record[cColumnItem(column).dataIndex] || '暂无' }}
									</template>
									<p class="font-14 tooltip-default-text">{{ record[cColumnItem(column).dataIndex] || '暂无' }}</p>
								</a-tooltip>
							</div>
							<div v-else>
								<a-tooltip placement="topLeft">
									<template #title>
										{{ tableAttr.searchObj.type === 1 ? record.firmwareVersion : record.softwareVersion }}
									</template>
									<p class="font-14 tooltip-default-text">
										{{ tableAttr.searchObj.type === 1 ? record.firmwareVersion : record.softwareVersion }}
									</p>
								</a-tooltip>
							</div>
						</template>
					</a-table>
				</div>
			</a-modal>
		</template>
	</ConfModuleContainer>
</template>

<script setup lang="ts" name="box-versions-detail">
import { g6UseTable } from 'glasssix-vue3-hooks';
import { g6Permission } from 'glasssix-utils-ts';
import { BoxVersionManageApi } from '../../api';
import { ConfModuleContainer } from '../../components/index';
import { Key } from '../../type';
const $message: any = inject('$message');

const router = useRouter();
const route = useRoute();

const { tableAttr, setTableData, setTablePagination } = g6UseTable(BoxVersionManageApi.getBoxUpdateLog);
const cType = computed(() => {
	const type = (route.query.type as string) === '1' ? '固件' : '软件';
	return `${type}`;
});
const currentTitle = computed(() => {
	const name = route.query?.roleName ?? '盒子版本';
	return `${name}`;
});
const showOperation = computed(() => {
	const filterResult = tableAttr.data.filter(function (item) {
		return item.status === 1;
	});
	console.log(filterResult); // [3,4,5]
	return filterResult.length > 0;
});

const columns: TsGlobalType.TsTableColumn[] = [
	{ dataIndex: 'boxName', title: '设备名称', width: 180, ellipsis: true },
	{ dataIndex: 'serial', title: 'SN码', width: 214, ellipsis: true },
	{ dataIndex: 'beforeVersion', title: '升级前版本号', width: 180, ellipsis: true },
	{ dataIndex: 'afterVersion', title: '升级后版本号', width: 180, ellipsis: true },
	{ dataIndex: 'status', title: '状态', custom: true, width: 180, ellipsis: true },
	{ dataIndex: 'createdTime', title: '时间', width: 192, sorter: true, ellipsis: true }
];

const cColumnItem = computed(() => {
	return function (params: any) {
		return params as TsGlobalType.TsTableColumn;
	};
});

const cStatus = computed(() => {
	return function name(val: number) {
		if (val === 0) {
			return '升级成功';
		}
		if (val === 1) {
			return '升级失败';
		}
		if (val === 2) {
			return '升级中';
		}
	};
});
const chooseDeviceVisible = ref<boolean>(false);
// 弹窗表格体
const tableRef = ref();
const tableContainer = ref<any>(null);
// 触底下一页
const isAtBottom = ref<boolean>(false);

// 弹窗内容
const rowKey = ref<string>('id');
const dialogSataSource = ref<Record<string, string>[]>([]);
const updateColumns: TsGlobalType.TsTableColumn[] = [
	{ dataIndex: 'boxName', title: '盒子名称', width: 120, ellipsis: true },
	{ dataIndex: 'serial', title: 'SN码', width: 226, ellipsis: true },
	{ dataIndex: 'version', title: '当前版本', custom: true, ellipsis: true }
];
// 翻页页码
const scrollPage = ref<number>(1);
// 页总数
const pageTotal = ref<number>(0);
// 选择升级设备表格接口
const getAllOnlineBoxInfoList = async (): Promise<void> => {
	chooseDeviceVisible.value = true;
	const param = {
		current: scrollPage.value,
		pageSize: 10,
		id: tableAttr.searchObj.id as string,
		type: tableAttr.searchObj.type as string
	};
	const res: TsRes = await BoxVersionManageApi.getAllOnlineBoxInfoList(param);
	dialogSataSource.value = [...dialogSataSource.value, ...res.data.records];

	pageTotal.value = res.data.total;
};
// 滚动触底翻页
const handleScroll = (): void => {
	// 当滚动高度和表格体高度相等时则为滚动到底部
	const height = tableContainer.value.scrollHeight - tableContainer.value.scrollTop;
	if (height === tableContainer.value.clientHeight) {
		// 只有isAtBottom为true时调用下一页内容
		isAtBottom.value = true;
		if (pageTotal.value === dialogSataSource.value.length) {
			return;
		}
		scrollPage.value++;

		getAllOnlineBoxInfoList();
	} else {
		isAtBottom.value = false;
	}
};
const upBoxDeviceRows = ref<Record<string, string>[]>([]);
const confirmLoading = ref<boolean>(false);
// 多选
const rowSelection = {
	onChange: (selectedRowKeys: Key[], selectedRows: Key[]) => {
		upBoxDeviceRows.value = selectedRows.map((item: any) => ({
			boxId: item.id,
			serial: item.serial,
			version: item.type === 1 ? item.firmwareVersion : item.softwareVersion
		}));
	}
};
// 关闭弹窗
const closeDeviceUpdate = (): void => {
	chooseDeviceVisible.value = false;
	scrollPage.value = 1;
	dialogSataSource.value = [];
	// 移除表格监听
	nextTick(() => {
		// 获取表格体
		tableContainer.value = tableRef?.value?.$el?.querySelector('.ant-table-body');
		tableContainer.value?.removeEventListener('scroll', handleScroll);
	});
};

const onSubmitName = async (): Promise<void> => {
	console.log('upBoxDeviceRows.value:', upBoxDeviceRows.value);

	if (upBoxDeviceRows.value.length !== 0) {
		confirmLoading.value = true;
		try {
			const param = {
				boxVersionId: tableAttr.searchObj.id as string,
				upBoxDeviceList: upBoxDeviceRows.value
			};
			// await nameFormRef.value?.validate();
			// nameFormRef.value?.resetFields();
			// $message.info('升级中');

			const res: TsRes = await BoxVersionManageApi.boxUpdateVersion(param);
			console.log('res:', res);
			if (res?.code === 0) {
				$message.success('操作成功');
				setTableData();
				closeDeviceUpdate();
			}
			confirmLoading.value = false;
			// emits('close');
		} catch (error) {
			console.error(error);
		}
	} else {
		$message.warning('请选中设备！');
	}
};

const PageButtonClick = async (btnCode: string, record: Record<string, any> = {}): Promise<void> => {
	if (btnCode === 'update-device') {
		getAllOnlineBoxInfoList();

		nextTick(() => {
			// console.log('-0-0-0-0-', tableRef?.value.$el.querySelector('.ant-table-body'));
			// 获取表格体
			tableContainer.value = tableRef?.value?.$el?.querySelector('.ant-table-body');
			tableContainer.value?.addEventListener('scroll', handleScroll);
		});
	}
	if (btnCode === 'upgrade-again') {
		$message.info('重新升级中');
		const res: TsRes = await BoxVersionManageApi.boxRestartUpdate(record.id);
		if (res.code === 0) {
			router.go(0);
		}
	}
};

// 排序
const sort = (val: any): void => {
	console.log('排序：', val);
	tableAttr.searchObj.timeSort = val.order;
	setTableData(true);
};

const versionDescription = ref<string>('');

onMounted(() => {
	versionDescription.value = route.query?.versionDescription as string;
	tableAttr.searchObj.id = route.query?.id as string;
	tableAttr.searchObj.type = route.query?.type as string;
	tableAttr.searchObj.timeSort = 'desc';

	setTableData();
});
</script>

<style lang="less" scoped>
// 当前页面不需要的话, 可删除 style标签
.detail-title {
	color: @text01;
}

.description-box {
	display: flex;
	width: 100%;
	height: 44px;
	margin-bottom: 12px;
	border-radius: 8px;
	padding: 10px 32px;
	background: @background04;

	.item {
		position: relative;
		display: flex;
		margin-right: 49px;
		line-height: 22px;

		.label {
			margin-right: 12px;
			color: @text03;
		}

		.value {
			color: @text02;
		}

		&::after {
			position: absolute;
			right: -24.5px;
			bottom: -2px;
			width: 1px;
			height: 24px;
			background-color: @borderColor02;
			content: '';
		}
	}

	.item:last-child {
		.value {
			overflow: hidden; //超出部分隐藏
			width: 512px;
			white-space: nowrap; //不换行
			text-overflow: ellipsis; //文本溢出显示省略号
		}

		&::after {
			display: none;
		}
	}
}

.action-box {
	width: 100%;
	height: 44px;
	margin-bottom: 20px;
	padding: 4px 0;
}

.type {
	display: flex;
	justify-content: flex-start;
	align-items: center;

	.type-dot {
		width: 6px;
		height: 6px;
		margin-right: 6px;
		border-radius: 50%;
		background: @danger01;
	}
}

.operation-item-btn {
	color: @link01;
	cursor: pointer;

	&:hover {
		color: #679ff6;
		opacity: 0.85;
		cursor: pointer;
	}

	&:active {
		color: #2f6bcb;
		cursor: pointer;
	}
}

.choose-device-update {
	.table-box {
		overflow-y: hidden;
		width: 520px;
		height: 261px;
		border: 1px solid @borderColor02;
		border-radius: 6px;

		:deep(.ant-table-cell-scrollbar) {
			display: none !important;
		}

		.tooltip-default-text {
			overflow: hidden;
			width: 100%;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		:deep(.ant-table-cell) {
			border-bottom: 1px solid @borderColor02 !important;
		}

		// 表格样式
		:deep(.ant-table) {
			.ant-table-selection-column {
				padding: 0 !important;
			}

			.ant-table-tbody {
				tr.ant-table-measure-row {
					// display: none;
					visibility: collapse;
				}

				tr {
					td {
						height: 38px !important;
						// min-height: 38px !important;
						// border-bottom: 1px solid @borderColor02 !important;
					}
				}

				tr:last-child {
					td {
						border-bottom: none !important;
					}
				}
			}
		}
	}
}
</style>
